package com.neusoft.elmboot.controller;

import com.neusoft.elmboot.po.UserCoupon;
import com.neusoft.elmboot.service.UserCouponService;
import com.neusoft.elmboot.util.response.ResultBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/elm/UserCouponController")
public class UserCouponController {
	
	@Autowired
	private UserCouponService userCouponService;
	
	/**
	 * 获取用户可用优惠券列表
	 */
	@RequestMapping("/available")
	public ResultBody getAvailableCoupons(@RequestParam String userId) {
		try {
			List<UserCoupon> coupons = userCouponService.getAvailableCoupons(userId);
			return ResultBody.success("获取可用优惠券成功", coupons);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultBody.error("获取可用优惠券失败：" + e.getMessage(), null);
		}
	}
	
	/**
	 * 获取用户所有优惠券
	 */
	@RequestMapping("/all")
	public ResultBody getAllCoupons(@RequestParam String userId) {
		try {
			List<UserCoupon> coupons = userCouponService.getUserCoupons(userId);
			return ResultBody.success("获取优惠券列表成功", coupons);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultBody.error("获取优惠券列表失败：" + e.getMessage(), null);
		}
	}
	
	/**
	 * 获取优惠券详情
	 */
	@RequestMapping("/detail")
	public ResultBody getCouponDetail(@RequestParam Integer couponId) {
		try {
			UserCoupon coupon = userCouponService.getCouponById(couponId);
			if (coupon == null) {
				return ResultBody.error("优惠券不存在", null);
			}
			return ResultBody.success("获取优惠券详情成功", coupon);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultBody.error("获取优惠券详情失败：" + e.getMessage(), null);
		}
	}
	
	/**
	 * 验证优惠券是否可用
	 */
	@RequestMapping("/validate")
	public ResultBody validateCoupon(@RequestParam Integer couponId, @RequestParam Double orderAmount) {
		try {
			boolean valid = userCouponService.validateCoupon(couponId, orderAmount);
			if (valid) {
				UserCoupon coupon = userCouponService.getCouponById(couponId);
				return ResultBody.success("优惠券有效", coupon);
			} else {
				return ResultBody.error("优惠券无效或已过期或不满足最低消费要求", null);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ResultBody.error("验证优惠券失败：" + e.getMessage(), null);
		}
	}
}
